<template>
  <div>
    <qa-dialog title="选择" v-model="show" :width="720">
      <el-divider />
      <el-tree
        style="max-width: 600px"
        :data="data"
        :props="defaultProps"
        @node-click="handleNodeClick"
      >
      <template #default="{ node, data }">
        <span class="custom-tree-node">
          <span >{{ node.label }}（{{ node.data.menu_id }}）</span>
        </span>
      </template>
    </el-tree>
      <template #footer>
        <div class="dialog-footer flex justify-end">
          <el-button type="primary" @click="treeSelectConfirm">确定</el-button>
          <el-button @click="close">关闭</el-button>
        </div>
      </template>
    </qa-dialog>
  </div>
</template>

<script setup lang="ts">
import qaDialog from './qa-dialog.vue';
import Http from '@/util/request'
const show = ref(false)
const emit = defineEmits(['treeSelectConfirm'])

const props = withDefaults(
  defineProps<{
    defaultProps?:any;
    action?: string;
    modelValue?: any;
  }>(),
  {
  }
)
const treeSelectConfirm = () => {
  emit('treeSelectConfirm', treeData.value)
  close()
}


watch(()=> props.modelValue,()=>{
  if(!list.value) return
  const findData = props.modelValue ? list.value.find((item:any) => item[props.defaultProps.value] === props.modelValue) : null;
  if(findData) emit('treeSelectConfirm', findData)
})

const data = ref([])
const list = ref([])
const getData = async () => {
  const res = await Http.request({
    url: props.action,
    method: 'post',
  })

  console.log('res',res)
  data.value = res.data.data.rows
  list.value = res.data.data.list
  const findData = props.modelValue ? res.data.data.list.find((item:any) => item[props.defaultProps.value] === props.modelValue) : null;
  if(findData) emit('treeSelectConfirm', findData)
}

const treeData = ref(null)

const handleNodeClick = (data: any) => {
  treeData.value = data
}

getData()

const open = () => {
  show.value = true
}

const close = () => {
  show.value = false
}

defineExpose({
  open,
  close
})

</script>

<style scoped></style>
